import json
import re
import random

from django.views import View
from django.http import JsonResponse, HttpResponse
from django_redis import get_redis_connection

from celery_tasks.sms.tasks import ccp_send_sms_code
from ihome.libs.captcha.captcha import captcha
from ihome.utils import statusCode


# 图形验证码
class ImageCodeView(View):

    def get(self, request):
        cur = request.GET.get('cur')
        # pre = request.GET.get('pre')

        # 生成图形验证码
        text, image = captcha.generate_captcha()
        print(text)

        # 保存图形验证码
        conn = get_redis_connection('verify_code')
        conn.setex('img_%s' % cur, 300, text)

        # 构建响应
        return HttpResponse(image, content_type='image/jpg')


# 短信验证码
class SMSCodeView(View):

    def post(self, request):



        # 提取参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        id = data.get('id')
        text = data.get('text')

        conn = get_redis_connection('verify_code')

        # 验证是否超过60秒
        flag = conn.get('flag_%s' % mobile)
        if flag:
            return JsonResponse({'code': statusCode.REQERR, 'errmsg': '请勿频繁发送'})

        # 校验参数
        if not all([mobile, id, text]):
            return JsonResponse({'errno': statusCode.PARAMERR, 'errmsg': '缺少必要参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': statusCode.PARAMERR, 'errmsg': '手机号格式错误'})

        if not re.match(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$', id):
            return JsonResponse({'errno': statusCode.PARAMERR, 'errmsg': '图片验证码编号错误'})

        # 业务校验
        image_code_redis = conn.get('img_%s' % id)

        # 防止验证码被重复校验
        conn.delete('img_%s' % id)

        if image_code_redis is None:
            return JsonResponse({'errno': statusCode.NODATA, 'errmsg': '图形验证码失效'})

        if text.lower() != image_code_redis.decode().lower():
            return JsonResponse({'errno': statusCode.PARAMERR, 'errmsg': '图形验证码错误'})

        # 生成短信验证码
        sms_code = '%06d' % random.randrange(0, 999999)

        # 保存短信验证码
        conn.setex('sms_%s' % mobile, 60, sms_code)

        # 发送短信
        ccp_send_sms_code.delay(mobile, sms_code)

        # 避免频繁发送短信
        conn.setex('flag_%s' % mobile, 60, 1)

        return JsonResponse({'errno': statusCode.OK, 'errmsg': '发送成功'})
